<template>
	<div class="exchange-coupon-container">
    <!-- <top-back :topBackParams="topBackParams"></top-back> -->
		<!-- 兑换优惠券列表-->
    <ul class="exchange-coupon" v-if="coupons.length>0">
      <van-list
          v-model="loading"
          :finished="finished"
          :error.sync="error"
          error-text="请求失败，点击重新加载"
          finished-text=""
          @load="onLoad"
        >
        <li v-for="(couponItem,index) in coupons" :key="index" class="coupons-li">
          <div class="coupons-item">
            <section :class="couponItem.coupon_type==3?'coupons-box coupon-pack':'coupons-box'">
              <section class="coupon-left">
                <h1 v-if="couponItem.promotion_type==1" :class="couponItem.coupon_type==3?'padding':''" class="coupon-price">{{couponItem.value}}<span class="txt">折</span></h1>
                <h1 v-else class="coupon-price" :class="couponItem.coupon_type==3?'padding':''" v-html="scaleGoodsPriceFn(couponItem.value)"></h1>
                <div v-if="couponItem.coupon_type!=3">
                  <p v-if="couponItem.at_least>0">满{{couponItem.at_least}}元使用</p>
                  <p v-else>不限订单金额</p>
                </div>
              </section>
              <section class="coupon-right">
                <section class="coupon-l">
                  <div class="name">
                    <h4>{{couponItem.title}}</h4>
                    <p class="time-str margin0" v-if="couponItem.limit_receive_time_str">{{couponItem.limit_receive_time_str}}</p>
                    <p class="margin0">{{couponItem.start_time}} 至 {{couponItem.end_time}}</p>
                  </div>
                  <span :class="couponItem.limit_receive_time_str?'explain time-pd':'explain'">仅在有限时间内使用</span>
                </section>
                <section class="coupon-r">
                  <span class="coupon-point"><i>{{couponItem.points}}</i>{{point_name}}</span>
                  <span v-if="u_points-couponItem.points>=0">
                    <van-button class="btn" v-if="couponItem.points==0" @click="clickExchange(couponItem)" color="linear-gradient(to right, #F82337, #FF2D59)" round >立即领取</van-button>
                    <van-button class="btn" v-else @click="clickExchange(couponItem)" color="linear-gradient(to right, #F82337, #FF2D59)" round >立即兑换</van-button>
                  </span>
                  <van-button class="btn" v-else color="linear-gradient(to right, #F82337, #FF2D59)" round >{{point_name}}不足</van-button>
                </section>
              </section>
            </section>
          <div class="coupon-tip" v-if="couponItem.description">{{couponItem.description}}</div>
          </div>
        </li>
      </van-list>
    </ul>
    
    <div v-else>
      <no-data :noData=noData></no-data>
      <!-- <img src="__MOBIMG__/user/quan1.png" width="24%" alt="">
      <p class="no_data_member">暂无未使用{{ftitle_coupon_name}}</p> -->
    </div>
    <van-dialog
        v-model="showSuccessPop"
        title=""
        :show-cancel-button="false"
        :closeOnPopstate="true"
        confirm-button-text="确定"
        @confirm='confirmSuccessPop'
        class="common-confirm"
        @close="closeSuccessPop"
      >
         <div class="success-con">
        <!-- <div class="diy_active_box"> -->
          <div class="box-icon">
            <img src="https://img.wifenxiao.com/h5-wfx/images/user/mycoupon/success_icon.png" alt="">
          </div>
          <div class="box-text"><span>{{successMsg}}</span>	</div>
          
        <!-- </div> -->
      </div>
    </van-dialog>
  </div>
</template>

<script>
  import Vue from 'vue'
  import { Dialog } from 'vant'
  import { activityCoupon, exchangeCoupon } from '@/api/user/member/memberApi'
  import { scaleGoodsPrice } from '@/utils/index'
  import { openPage } from '@/utils/utils'
  import TopBack from '@/components/TopBack/index'
  import noData from '@/components/noData/index'
  // import noDataImg from '@img/no-coupon.png'
  import Store from '@/utils/store'
  export default Vue.extend({
    components: {
      TopBack,
      noData
    },
    data() {
      return {
        topBackParams: {
          headerTitle: '兑换优惠券',
          bgColor: '#ffffff',
          titleSize: '16px',
          fontWeight: 'bold',
          backLink: ''
        },
        noData: {
          img: 'https://img.wifenxiao.com/h5-wfx/images/no-coupon.png',
          text: '暂无优惠券',
          marginTop: '120px'
        },
        showSuccessPop: false,
        successMsg: '恭喜您，兑换成功',
        point_name: '积分',
        u_points: '',
        coupons: [
          /* {
            not_start: '',
            value: '22',
            points: '33',
            coupon_type: '1',
            at_least: '2',
            title: '优惠券名称',
            start_time: '2019-01-01',
            end_time: '2019-10-10',
            barcode: '1',
            couponverify_link: '',
            is_share: 0,
            link_share: '',
            user_coupon_pack_id: '',
            description: '优惠券描述'
          } */
        ],
        loading: false,
        finished: false,
        error: false,
        p: 2,
        cid: '',
        orderId: '',
        exchangeResData: ''
      }
    },
    methods: {
      init() {
        const baseData = {
          sid: this.$store.getters.sid || Store.fetchLocal('sid'),
          pid: this.$store.getters.pid || Store.fetchLocal('pid')
        }
        // TODO 路径修改
        this.topBackParams.backLink = 'mycoupon?sid=' + baseData.sid + '&pid=' + baseData.pid
        this.$loadingWrap.show()
        setTimeout(() => {
          this.$loadingWrap.close()
        }, 10000)
        const params = { cid: this.cid, order_id: this.orderId }
        activityCoupon(params).then(res => {
          this.$loadingWrap.close()
          if (res.status == 1) {
            this.point_name = res.data.point_name
            this.u_points = res.data.u_points
            this.coupons = res.data.list
            if (this.coupons.length == 0 && this.cid) {
              this.noData.text = `暂无权限领取该${res.data.ftitle_coupon_name}`
            }
          } else {
            this.$Error(res.msg)
          }
        })
      },
      onLoad() {
        if (this.finished) return false
        this.loading = true
        const data = {
          p: this.p,
          cid: this.cid
        }
        activityCoupon(data)
          .then(res => {
            this.loading = false
            if (res.data.list.length > 0) {
              this.coupons.push(...res.data.list)
              this.p++
            } else {
              this.finished = true
            }
          })
          .catch(() => {
            this.error = true
          })
      },
      scaleGoodsPriceFn(price, className) {
        return scaleGoodsPrice(price, className,1)
      },
      // 关闭兑换优惠券成功弹窗
      closeSuccessPop() {
        this.showSuccessPop = false
      },
      confirmSuccessPop() {
        this.showSuccessPop = false
        if (this.exchangeResData.url) {
            openPage(this.exchangeResData.url,1)
        } else {
            // TODO 返回
            wx.navigateBack({
              delta: 1
            })
             // TODO 小程序端触发会员中心和优惠券列表更新页面
             window.$$publish('refreshCoupon', true)
        }
      },
      // 领取和兑换优惠券
      clickExchange(item) {
        let dialogTitle = ''
        if (item.coupon_type == 3) {
          dialogTitle = '确定兑换此大礼包？'
        } else {
          if (item.points > 0) {
            dialogTitle = '确定兑换此优惠券？'
            this.successMsg = '恭喜您，兑换成功'
          } else {
            dialogTitle = '确定领取此优惠券？'
            this.successMsg = '恭喜您，领取成功'
          }
        }
        Dialog.confirm({
          // title: '标题',
          message: dialogTitle,
          className: 'common-confirm',
          confirmButtonText: '确定',
          closeOnClickOverlay: true
        }).then(() => {
          this.$loadingWrap.show()
          setTimeout(() => {
            this.$loadingWrap.close()
          }, 10000)
          const params = { id: item.coupon_id }
          exchangeCoupon(params).then(res => {
            this.$loadingWrap.close()
            if (res.status == 1) {
              this.exchangeResData = res.data
              this.showSuccessPop = true
          
              // this.$Error(res.msg)
            } else {
              this.$Error(res.msg)
            }
          })
        // on confirm
        }).catch(() => {
        // on cancel
        })
      }
    },
    created() {
      if (this.$route.query.cid) {
        this.cid = this.$route.query.cid
        this.orderId = this.$route.query.order_id
      }
      this.init()
    },
    mounted() {
      // 小程序触底加载更多
      window.addEventListener('reachbottom', () => {
        this.onLoad()
      })
    }
  })
</script>

<style lang="scss">
  @import "../../../../../styles/mixin";
  @import '../../../../../styles/user/coupons/index.scss';
  .exchange-coupon-container{
    ul{
      padding:20px;
    }
    li{
      overflow:hidden;
    }
    .coupon-r{
      // margin-top:14px;
      .coupon-point{
        display: block;
        font-size: 24px;
        color: #F30C23;
        i{
          display: block;
          font-size: 28px;
          font-weight: bold;
        }
      }
    }
    .success-con{
      padding:46px 0 54px;
      font-size:32px;
      text-align:center;
      .box-icon{
        width:223px;
        height:191px;
        margin:0 auto 40px;
        img{
          display:block;
          width:100%;
        }
      }
      .box-text{
        line-height:1.2;
      }
    }
    .time-str{
      margin-top: 0!important;
      top: 14px;
    }
    .time-pd{
      // margin-bottom: 20px;
    }
    .margin0 {
      margin-top: 0!important;
    }
  }
</style>